package com.starrocks.controller;

import com.starrocks.common.Result;
import com.starrocks.entity.SyncConfigEntity;
import com.starrocks.entity.SyncTargetEntity;
import com.starrocks.service.SyncConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 同步配置管理 Controller
 * 提供配置的增删改查接口
 */
@Slf4j
@RestController
@RequestMapping("/api/config")
public class SyncConfigController {
    
    @Autowired
    private SyncConfigService syncConfigService;
    
    /**
     * 查询所有配置（包含目标表）
     */
    @GetMapping("/list")
    public Result<List<SyncConfigEntity>> listConfigs() {
        try {
            List<SyncConfigEntity> configs = syncConfigService.list();
            
            // 为每个配置加载目标表列表
            for (SyncConfigEntity config : configs) {
                List<SyncTargetEntity> targets = syncConfigService.listTargetsByConfigId(config.getId());
                config.setTargets(targets);
            }
            
            return Result.success(configs);
        } catch (Exception e) {
            log.error("查询配置列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有启用的配置（包含目标表）
     */
    @GetMapping("/list-enabled")
    public Result<List<SyncConfigEntity>> listEnabledConfigs() {
        try {
            List<SyncConfigEntity> configs = syncConfigService.listEnabledConfigs();
            return Result.success(configs);
        } catch (Exception e) {
            log.error("查询启用配置失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询配置详情（包含目标表）
     */
    @GetMapping("/{id}")
    public Result<SyncConfigEntity> getConfig(@PathVariable Long id) {
        try {
            SyncConfigEntity config = syncConfigService.getById(id);
            if (config != null) {
                config.setTargets(syncConfigService.listTargetsByConfigId(id));
            }
            return Result.success(config);
        } catch (Exception e) {
            log.error("查询配置详情失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建或更新配置（包含目标表）
     */
    @PostMapping("/save")
    public Result<SyncConfigEntity> saveConfig(@RequestBody SyncConfigEntity config) {
        try {
            boolean success = syncConfigService.saveWithTargets(config);
            if (success) {
                return Result.success("保存成功", config);
            } else {
                return Result.error("保存失败");
            }
        } catch (Exception e) {
            log.error("保存配置失败", e);
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除配置
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteConfig(@PathVariable Long id) {
        try {
            boolean success = syncConfigService.deleteWithTargets(id);
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除配置失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 启用/禁用配置
     */
    @PostMapping("/{id}/toggle")
    public Result<Boolean> toggleConfig(@PathVariable Long id) {
        try {
            SyncConfigEntity config = syncConfigService.getById(id);
            if (config != null) {
                config.setEnabled(!config.getEnabled());
                boolean success = syncConfigService.updateById(config);
                if (success) {
                    return Result.success("状态已更新", config.getEnabled());
                } else {
                    return Result.error("更新失败");
                }
            } else {
                return Result.error(404, "配置不存在");
            }
        } catch (Exception e) {
            log.error("切换配置状态失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
}
